# coding:utf-8
import urllib.request

from time import sleep
from common.loggermgr import LoggerManager

logger = LoggerManager().getLogger("message_dump_alarm")

TRY_TIMES = 3


def send_sms_by_cloudkilling(nums, msg):
    """
    nums: 字符串,逗号分隔. 137xxxx,159xxxx
    msg: unicode
    """
    url = 'http://ckw.kisops.com:9080/tools/send_msg/'
    times = TRY_TIMES
    while True:
        if times <= 0:
            logger.info(
                "failed send message,call interface over %s times" % TRY_TIMES)
            break
        times -= 1
        try:
            request = urllib.request.Request(url)
            response = urllib.request.urlopen(
                request, urllib.urlencode({
                    'nums': nums,
                    'msg': msg.encode('utf8'),
                })
            )
            ret = response.read()
            logger.info("send msg stat:[%s],msg:[%s]" % (ret, msg[:20]))
            if str(ret).find("message api error") != -1:
                sleep(2)
                continue
            count = len(msg)
            if count > 20:
                print(u'send_msg success: %s...' % msg[:20])
            else:
                print(u'send_msg success: %s' % msg)
            return ret == u"ok"
        except Exception as e:
            print('send_msg error: %s' % e)
            logger.info('send_msg error: %s' % e)
            sleep(2)
        return False


if __name__ == '__main__':
    send_sms_by_cloudkilling("18688165618", "test")
